package com.yixuan.mt.core;

import com.yixuan.mt.common.properties.GlobalProperties;
import com.yixuan.mt.core.handler.BeforeControllerHandler;
import com.yixuan.mt.core.handler.RequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Main {

    @Autowired
    GlobalProperties globalProperties;

    @Autowired
    private BeforeControllerHandler beforeControllerHandler;

    @Autowired
    private RequestHandler requestHandler;

    @PostConstruct
    public void loop() {
        new ServerBootstrap().group(new NioEventLoopGroup(), new NioEventLoopGroup(2)).localAddress(globalProperties.getHost(), globalProperties.getPort()).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) {
                ch.pipeline().addLast(new HttpServerCodec());
                ch.pipeline().addLast(beforeControllerHandler);
                ch.pipeline().addLast(requestHandler);
            }
        }).bind();
    }
}
